package com.zhuoyue.web.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.zhuoyue.biz.core.api.dao.DeviceDao;
import com.zhuoyue.biz.core.api.domain.DeviceDO;
import com.zhuoyue.common.aop.auth.CheckLogin;
import com.zhuoyue.common.aop.auth.User;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.zhuoyue.common.dto.ControllerResult;

import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;


/**
 * 消息日志
 *
 * @author Administrator
 */
@RestController
@Scope("prototype")
@RequestMapping("/api/message")
@Validated
public class AppMessageController {

    @Autowired
    private DeviceDao deviceDao;

    @Value("${rest-template.ip}")
    private String ip;
    @Value("${rest-template.port}")
    private String port;

    private String getUrl(String ip, String port) {
        return "http://" + ip + ":" + port;
    }

    /**
     * 设备OD类型
     */
    private static final String OD_0FC8 = "0FC8";
    private static final String DEVICE_TYPE_04 = "04";
    private static final String DELETE_SUCCESS = "删除成功";
    private static final String DELETE_FAIL = "删除失败";

    /**
     * 查询日志列表
     * 获取用户信息列表(6:账号安全  7:普通类消息 8:系统消息)
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/user")
    @CheckLogin
    public ControllerResult getUserMessageList(@RequestParam("pageNum") Integer pageNum,
                                               @RequestParam("pageSize") Integer pageSize,
                                               @RequestParam("messageType") String messageType,
                                               HttpServletRequest request) {
        String userUrl = getUrl(ip, port) + "/api/message/user?";
        User user = (User) request.getAttribute("user");
        RestTemplate restTemplate = new RestTemplate();
        userUrl = userUrl + "pageNum=" + pageNum + "&pageSize=" + pageSize + "&userId=" + user.getId() + "&messageType=" + messageType;
        ResponseEntity<R> forEntity = restTemplate.getForEntity(userUrl, R.class);
        return ControllerResult.toReturnDataSuccess("查询成功", forEntity.getBody().getData());
    }


    /**
     * 查询消息未读数量
     * <p>
     * messageType
     *
     * @return
     */
    @GetMapping("/unReadSystemMessageCount")
    @CheckLogin
    public ControllerResult getunReadSystemMessageCount(@NotBlank(message = "消息类型不能为空") String messageType,
                                                        HttpServletRequest request) {
        String userUrl = getUrl(ip, port) + "/api/message/unReadSystemMessageCount?";
        User user = (User) request.getAttribute("user");
        RestTemplate restTemplate = new RestTemplate();
        userUrl = userUrl + "&userId=" + user.getId() + "&messageType=" + messageType;
        ResponseEntity<R> forEntity = restTemplate.getForEntity(userUrl, R.class);
        return ControllerResult.toReturnDataSuccess("查询成功", forEntity.getBody().getData());
    }

    @PutMapping("/updateHasRead")
    @CheckLogin
    public ControllerResult updateHasRead(@NotBlank(message = "消息类型不能为空") String messageType,
                                          HttpServletRequest request) {
        String userUrl = getUrl(ip, port) + "/api/message/updateHasRead?";
        User user = (User) request.getAttribute("user");
        RestTemplate restTemplate = new RestTemplate();
        userUrl = userUrl + "&userId=" + user.getId() + "&messageType=" + messageType;
        restTemplate.put(userUrl, null);
        return ControllerResult.toReturnMessageSuccess("修改成功");
    }


    /**
     * 获取设备的日志信息,普通分页查询信息
     *
     * @param pageNum
     * @param pageSize
     * @param startTime
     * @param deviceMac
     * @param gatewayMac
     * @param endTime
     * @return
     */
    @GetMapping("/device")
    @CheckLogin
    public ControllerResult getUserMessageList(@RequestParam("pageNum") Integer pageNum,
                                               @RequestParam("pageSize") Integer pageSize,
                                               @RequestParam("start") long startTime,
                                               @RequestParam("end") long endTime,
                                               @RequestParam("deviceMac") String deviceMac,
                                               @RequestParam("gatewayMac") String gatewayMac) {
        String deviceUrl = "";
        RestTemplate restTemplate = new RestTemplate();
        DeviceDO deviceDO = deviceDao.selectByMac(deviceMac);
        switch (StringUtils.upperCase(deviceDO.getOdIndex() + deviceDO.getDeviceType() + deviceDO.getProductType())) {
            case "0FBEA002":
            case "0FB40102":
                deviceUrl = getUrl(ip, port) + "/data/sensirion/log/by/time/slot?";
                break;
            default:
                deviceUrl = getUrl(ip, port) + "/api/security/device?";
                break;
        }
        deviceUrl = deviceUrl + "pageNum=" + pageNum + "&pageSize=" + pageSize + "&deviceMac=" + deviceMac + "&gatewayMac=" + gatewayMac + "&start=" + startTime + "&end=" + endTime;
        ResponseEntity<R> forEntity = restTemplate.getForEntity(deviceUrl, R.class);
        return ControllerResult.toReturnDataSuccess("查询成功", forEntity.getBody().getData());
    }


    /**
     * 获取当日的设备信息，APP一进来显示的当天的数据信息
     *
     * @param deviceMac
     * @param gatewayMac
     * @return
     */
    @GetMapping("/device/today")
    @CheckLogin
    public ControllerResult selectToday(@NotBlank(message = "设备的MAC地址不能为空") @RequestParam("deviceMac") String deviceMac,
                                        @NotBlank(message = "网关的MAC地址不能为空") @RequestParam("gatewayMac") String gatewayMac) {
        String deviceUrl = "";
        RestTemplate restTemplate = new RestTemplate();
        DeviceDO deviceDO = deviceDao.selectOne(Wrappers.<DeviceDO>lambdaQuery().eq(DeviceDO::getZigbeeMac, deviceMac));
        if (deviceDO == null) {
            return ControllerResult.toNoDataFail("数据不存在");
        }
        ResponseEntity<R> forEntity = null;
        switch (StringUtils.upperCase(deviceDO.getOdIndex() + deviceDO.getDeviceType() + deviceDO.getProductType())) {
            //温湿度
            case "0FBEA002":
                //温湿度
            case "0FB40102":
                deviceUrl = getUrl(ip, port) + "/data/sensirion/log/today?";
                break;
            default:
                deviceUrl = getUrl(ip, port) + "/api/security/today?";
                break;
        }
        deviceUrl = deviceUrl + "&deviceMac=" + deviceMac + "&gatewayMac=" + gatewayMac;
        forEntity = restTemplate.getForEntity(deviceUrl, R.class);
        if (forEntity == null) {
            return ControllerResult.toNoDataFail("数据不存在");
        }
        return ControllerResult.toReturnDataSuccess("查询成功", forEntity.getBody().getData());
    }

    /**
     * 获取某日的设备信息
     *
     * @param deviceMac
     * @param gatewayMac
     * @return
     */
    @GetMapping("/device/day")
    @CheckLogin
    public ControllerResult selectDay(@NotBlank(message = "设备的MAC地址不能为空") @RequestParam("deviceMac") String deviceMac,
                                      @NotBlank(message = "网关的MAC地址不能为空") @RequestParam("gatewayMac") String gatewayMac,
                                      @RequestParam("time") long time) {
        String deviceUrl = "";
        DeviceDO deviceDO = deviceDao.selectOne(Wrappers.<DeviceDO>lambdaQuery().eq(DeviceDO::getZigbeeMac, deviceMac));
        switch (StringUtils.upperCase(deviceDO.getOdIndex() + deviceDO.getDeviceType() + deviceDO.getProductType())) {
            //温湿度
            case "0FBEA002":
                //温湿度
            case "0FB40102":
                deviceUrl = getUrl(ip, port) + "/data/sensirion/log/day?";
                break;
            default:
                deviceUrl = getUrl(ip, port) + "/api/security/day?";
                break;
        }

        RestTemplate restTemplate = new RestTemplate();
        deviceUrl = deviceUrl + "&deviceMac=" + deviceMac + "&gatewayMac=" + gatewayMac + "&time=" + time;
        ResponseEntity<R> forEntity = restTemplate.getForEntity(deviceUrl, R.class);
        return ControllerResult.toReturnDataSuccess("查询成功", forEntity.getBody().getData());
    }

    /**
     * 获取设备的日志总数，折线图
     *
     * @param startTime
     * @param deviceMac
     * @param gatewayMac
     * @param endTime
     * @return
     */
    @GetMapping("/device/count")
    @CheckLogin
    public ControllerResult selectTimeCount(@NotNull(message = "开始时间不能为空") @RequestParam("start") Long startTime,
                                            @NotNull(message = "结束时间不能为空") @RequestParam("end") Long endTime,
                                            @NotBlank(message = "设备的MAC地址不能为空") @RequestParam("deviceMac") String deviceMac,
                                            @NotBlank(message = "网关的MAC地址不能为空") @RequestParam("gatewayMac") String gatewayMac) {
        String deviceUrl = getUrl(ip, port) + "/api/security/count?";
        RestTemplate restTemplate = new RestTemplate();
        deviceUrl = deviceUrl + "&deviceMac=" + deviceMac + "&gatewayMac=" + gatewayMac + "&start=" + startTime + "&end=" + endTime;
        ResponseEntity<R> forEntity = restTemplate.getForEntity(deviceUrl, R.class);
        return ControllerResult.toReturnDataSuccess("查询成功", forEntity.getBody().getData());
    }


    /**
     * 获取单个设备的电量日志信息
     *
     * @return
     */
    @GetMapping("/metering")
    @CheckLogin
    public ControllerResult getSecurityLogListForDevice(@NotBlank(message = "设备MAC地址不能为空！") String deviceMac,
                                                        @NotNull(message = "请选择日期时间") Long time) throws ParseException {

        List<DeviceDO> deviceDos = deviceDao.selectList(Wrappers.<DeviceDO>lambdaQuery().eq(DeviceDO::getZigbeeMac, deviceMac));
        if (CollectionUtils.isEmpty(deviceDos) || !OD_0FC8.equals(deviceDos.get(0).getOdIndex()) || !DEVICE_TYPE_04.equals(deviceDos.get(0).getDeviceType())) {
            return ControllerResult.toParamFail("请检查设备是否正确！");
        }

        String deviceUrl = getUrl(ip, port) + "/api/metering/device/message?";
        RestTemplate restTemplate = new RestTemplate();
        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(time / 1000, 0, ZoneOffset.ofHours(8));
        String localTimeStart = StringUtils.substringBefore(localDateTime.toString(), "T") + " 00:00:00";
        String localTimeEnd = StringUtils.substringBefore(localDateTime.toString(), "T") + " 23:59:59";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateStart = simpleDateFormat.parse(localTimeStart);
        Date dateEnd = simpleDateFormat.parse(localTimeEnd);
        Long startTime = dateStart.getTime();
        Long endTime = dateEnd.getTime();
        deviceUrl = deviceUrl + "&deviceMac=" + deviceMac + "&start=" + startTime + "&end=" + endTime;
        ResponseEntity<R> forEntity = restTemplate.getForEntity(deviceUrl, R.class);
        return ControllerResult.toReturnDataSuccess("查询成功", forEntity.getBody().getData());
    }

    @GetMapping("/temperatureControl/log")
//    @CheckLogin
    public ControllerResult getTemperatureControlLog(@NotBlank String gatewayMac, @NotBlank String deviceMac,
                                                     @NotNull Integer pageNum, @NotNull Integer pageSize, long time) {
        String url = getUrl(ip, port) + "/data/temperatureControl/log/get?";
        RestTemplate restTemplate = new RestTemplate();

        url = url + "&gatewayMac=" + gatewayMac + "&deviceMac=" + deviceMac + "&pageNum="
                + pageNum + "&pageSize=" + pageSize + "&time=" + time;

        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.GET, null, Map.class);
        return ControllerResult.toReturnDataSuccess("成功", response.getBody());
    }


    /**
     * 根据用户id删除推送日志
     *
     * @return
     */
    @DeleteMapping("/remove/userLog")
    @CheckLogin
    public ControllerResult deleteTblMessageLogForUserId(HttpServletRequest request, @NotBlank(message = "消息类型不能为空") String messageType) {
        User user = (User) request.getAttribute("user");
        String url = getUrl(ip, port) + "/api/message/deleteAll/userId?";
        RestTemplate restTemplate = new RestTemplate();

        url = url + "&userId=" + user.getId() + "&messageType=" + messageType;

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, null, String.class);
        String result = response.getBody();

        if (DELETE_SUCCESS.equals(result)) {
            return ControllerResult.toReturnMessageSuccess(result);
        }
        if (DELETE_FAIL.equals(result)) {
            return ControllerResult.toSysErrorFail(result);
        }
        return ControllerResult.toReturnMessageSuccess(result);
    }

    /**
     * 根据选中id删除推送日志
     *
     * @return
     */
    @DeleteMapping("/userLog/list")
    @CheckLogin
    public ControllerResult deleteTblMessageLogForIds(@RequestBody List<String> ids) throws ParseException {


        String url = getUrl(ip, port) + "/api/message/delete/ids";
        RestTemplate restTemplate = new RestTemplate();


        HttpEntity<List<String>> request = new HttpEntity<>(ids);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, request, String.class);
        String result = response.getBody();
        if (DELETE_SUCCESS.equals(result)) {
            return ControllerResult.toReturnMessageSuccess(result);
        }
        if (DELETE_FAIL.equals(result)) {
            return ControllerResult.toSysErrorFail(result);
        }
        return ControllerResult.toReturnMessageSuccess(result);
    }


    /**
     * 以下为报警日志删除
     */
    /**
     * 根据设备Mac删除报警日志
     *
     * @return
     */
    @DeleteMapping("/securityLog")
    @CheckLogin
    public ControllerResult deleteTblSecurityLogForDeviceMac(@NotBlank(message = "deviceMac不能为空！") @RequestParam("deviceMac") String deviceMac) throws ParseException {
        String url = getUrl(ip, port) + "/api/security/deleteAll/deviceMac?";
        RestTemplate restTemplate = new RestTemplate();

        url = url + "&deviceMac=" + deviceMac;

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, null, String.class);
        String result = response.getBody();
        if (DELETE_SUCCESS.equals(result)) {
            return ControllerResult.toReturnMessageSuccess(result);
        }
        if (DELETE_FAIL.equals(result)) {
            return ControllerResult.toSysErrorFail(result);
        }
        return ControllerResult.toReturnMessageSuccess(result);
    }

    /**
     * 根据选中id删除推送日志
     *
     * @return
     */
    @DeleteMapping("/securityLog/ids")
    @CheckLogin
    public ControllerResult deleteTblSecurityLogForIds(@RequestBody List<String> ids) throws ParseException {

        String url = getUrl(ip, port) + "/api/security/delete/ids";
        RestTemplate restTemplate = new RestTemplate();

        HttpEntity<List<String>> request = new HttpEntity<>(ids);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, request, String.class);
        String result = response.getBody();
        if (DELETE_SUCCESS.equals(result)) {
            return ControllerResult.toReturnMessageSuccess(result);
        }
        if (DELETE_FAIL.equals(result)) {
            return ControllerResult.toSysErrorFail(result);
        }
        return ControllerResult.toReturnMessageSuccess(result);
    }

    /**
     * 以下为电量日志删除
     */
    /**
     * 根据设备Mac删除报警日志
     *
     * @return
     */
    @DeleteMapping("/meteringLogs")
    @CheckLogin
    public ControllerResult deleteTblMeteringForDeviceMac(@NotBlank(message = "deviceMac不能为空！") @RequestParam("deviceMac") String deviceMac) throws ParseException {
        String url = getUrl(ip, port) + "/api/metering/deleteAll/deviceMac?";
        RestTemplate restTemplate = new RestTemplate();

        url = url + "&deviceMac=" + deviceMac;

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, null, String.class);
        String result = response.getBody();
        if (DELETE_SUCCESS.equals(result)) {
            return ControllerResult.toReturnMessageSuccess(result);
        }
        if (DELETE_FAIL.equals(result)) {
            return ControllerResult.toSysErrorFail(result);
        }
        return ControllerResult.toReturnMessageSuccess(result);
    }

    /**
     * 根据选中id删除推送日志
     *
     * @return
     */
    @DeleteMapping("/meteringLog")
    @CheckLogin
    public ControllerResult deleteTblMeteringLogForIds(@RequestBody List<String> ids) throws ParseException {
        String url = getUrl(ip, port) + "/api/metering/delete/ids";
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<List<String>> request = new HttpEntity<>(ids);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, request, String.class);
        String result = response.getBody();
        if (DELETE_SUCCESS.equals(result)) {
            return ControllerResult.toReturnMessageSuccess(result);
        }
        if (DELETE_FAIL.equals(result)) {
            return ControllerResult.toSysErrorFail(result);
        }
        return ControllerResult.toReturnMessageSuccess(result);
    }


}
